#include "app_porting.h"

int32_t stm32_flash_read(uint32_t addr, uint8_t *buf, uint32_t len )
{
	uint32_t i;
	uint32_t *p;
	uint32_t *pa;
	
	if((0!=addr%4)||(0!=len%4)||(NULL==buf)){
		return LS_FAIL;
	}
	
	p=(uint32_t*)buf;
	pa=(uint32_t*)addr;
	len/=4;
	for(i=0;i<len;i++){
		*p++=*pa++;
	}
	
	return LS_SUCCESS;	
}

int32_t stm32_flash_write(uint32_t addr, uint8_t *buf, uint32_t len)
{
	uint32_t i;

	if((0!=addr%4)||(0!=len%4)||(NULL==buf)){
		return LS_FAIL;
	}
	
	FLASH_Unlock();
	FLASH_ClearFlag(FLASH_FLAG_EOP | FLASH_FLAG_PGERR | FLASH_FLAG_WRPRTERR);
	for(i=0;i<len;i+=4){
		if(FLASH_COMPLETE!=FLASH_ProgramWord(addr+i, *(uint32_t*)&buf[i])){
			FLASH_Lock();
			return LS_FAIL;
		}
	}
	FLASH_Lock();

	return LS_SUCCESS;
}

int32_t stm32_flash_erase(uint32_t addr, uint32_t page_num)
{
	uint32_t i;

	if((0!=addr%FLASH_PAGE_SIZE)
		||(0==page_num)){
		return LS_FAIL;		
	}

	FLASH_Unlock();
	FLASH_ClearFlag(FLASH_FLAG_EOP | FLASH_FLAG_PGERR | FLASH_FLAG_WRPRTERR);
	for(i=0;i<page_num;i++){
		if(FLASH_COMPLETE!=FLASH_ErasePage(addr)){
			FLASH_Lock();
			return LS_FAIL;
		}
		addr+=FLASH_PAGE_SIZE;

	}
	FLASH_Lock();

	return LS_SUCCESS;
}

